﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace lhhp.net.Utility.Sort
{
    /// <summary>
    /// lsfe
    /// </summary>
    public static class SortUtility
    {
        #region Bubble

        /// <summary>
        /// bubble sort|冒泡排序
        /// </summary>
        /// <typeparam name="T">要排序的数据元素类型</typeparam>
        /// <param name="sortArr">要排序的数组</param>
        /// <param name="order">排序的顺序（升序还是降序）</param>
        public static void BubbleSort<T>(T[] sortArr, SortOrder order) where T : IComparable<T>
        {
            bool exchanged;
            for (int i = 0; i < sortArr.Length; i++)
            {
                exchanged = false;
                for (int j = i; j < sortArr.Length - 1; j++)
                {
                    int result = sortArr[j].CompareTo(sortArr[j + 1]);
                    switch (order)
                    {
                        case SortOrder.Asc:
                            {
                                if (result > 0)
                                {
                                    T temp = sortArr[j];
                                    sortArr[j] = sortArr[j + 1];
                                    sortArr[j + 1] = temp;
                                    exchanged = true;
                                }
                                break;
                            }
                        case SortOrder.Desc:
                            {
                                if (result < 0)
                                {
                                    T temp = sortArr[j];
                                    sortArr[j] = sortArr[j + 1];
                                    sortArr[j + 1] = temp;
                                    exchanged = true;
                                }
                                break;
                            }
                        default:
                            break;
                    }
                }
                if (!exchanged)
                {
                    break;
                }
            }
        }
        public static void BubbleSort(int[] sortArr, SortOrder order)
        {
            BubbleSort<int>(sortArr, order);
        }
        public static void BubbleSort(float[] sortArr, SortOrder order)
        {
            BubbleSort<float>(sortArr, order);
        }
        public static void BubbleSort(double[] sortArr, SortOrder order)
        {
            BubbleSort<double>(sortArr, order);
        }
        public static void BubbleSort(string[] sortArr, SortOrder order)
        {
            BubbleSort<string>(sortArr, order);
        }

        #endregion
        
    }
}
